<template>
  <el-container>
    <el-aside width="200px" v-loading="deptLoading">
      <el-container>
        <el-header>
          <el-input
              v-model="deptName"
              placeholder="请输入部门名称"
              clearable
              size="default"
              prefix-icon="el-icon-search"
          />
        </el-header>
        <el-main class="nopadding">
          <el-tree
              class="menu"
              ref="tree"
              node-key="deptId"
              default-expand-all
              highlight-current
              :current-node-key="''"
              :data="deptList"
              :props="deptProps"
              :expand-on-click-node="false"
              :filter-node-method="deptFilterNodeMethod"
              @node-click="handleDeptClick"
          />
        </el-main>
      </el-container>
    </el-aside>

    <el-container>
      <el-header>
        <div class="left-panel">
          <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              @click="handleAdd"
          >新增
          </el-button>
          <el-button
              type="success"
              plain
              icon="el-icon-edit"
              :disabled="single"
              @click="handleUpdate"
          >修改
          </el-button>
          <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              :disabled="multiple"
              @click="handleDelete"
          >删除
          </el-button>
        </div>
        <div class="right-panel">
          <jcx-table-bar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></jcx-table-bar>
        </div>
      </el-header>

      <el-main>
        <el-form :model="queryParams" ref="queryForm" size="default" :inline="true" v-show="showSearch"
                 label-width="68px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="用户名称" prop="username">
                <el-input
                    v-model="queryParams.username"
                    placeholder="请输入部门名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="用户状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="部门状态" clearable>
                  <el-option key="1" label="启用" :value="true"/>
                  <el-option key="0" label="停用" :value="false"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <el-table ref="table" v-loading="loading" :data="userList" row-key="userId"
                  @selection-change="handleSelectionChange"
                  :stripe="config.stripe" :border="config.border" :size="config.size" style="width: 100%">
          <el-table-column type="selection"></el-table-column>
          <el-table-column label="用户标识" align="center" prop="userCode" v-if="columns[0].visible"></el-table-column>
          <el-table-column label="用户名称" align="center" prop="username" v-if="columns[1].visible"></el-table-column>
          <el-table-column label="用户昵称" align="center" prop="nickName" v-if="columns[2].visible"></el-table-column>
          <el-table-column label="联系电话" align="center" prop="phone" v-if="columns[3].visible"></el-table-column>
          <el-table-column label="联系邮箱" align="center" prop="email" v-if="columns[4].visible"></el-table-column>
          <el-table-column label="用户性别" align="center" prop="sex" v-if="columns[5].visible">
            <template #default="props">
              <el-tag v-if="props.row.sex === 0" type="info">女</el-tag>
              <el-tag v-if="props.row.sex === 1" type="warning">男</el-tag>
              <el-tag v-if="props.row.sex === 2" type="danger">保密</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="status" v-if="columns[6].visible">
            <template #default="props">
              <el-tag v-if="props.row.status" type="success">启用</el-tag>
              <el-tag v-if="!props.row.status" type="danger">停用</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[7].visible"></el-table-column>
          <el-table-column label="备注" align="center" prop="remark" v-if="columns[8].visible"></el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="props">
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(props.row)"
              >修改
              </el-button>
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(props.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <jcx-page
            v-show="total>0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
        ></jcx-page>

        <el-dialog destroy-on-close append-to-body width="900px" :title="title" v-model="open"
                   :close-on-click-modal="false" @closed="cancel">
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-row>
              <el-col :span="12">
                <div style="text-align: center;">
                  <span v-if="imgUrl === null">待上传头像</span>
                  <el-image
                      v-else
                      style="width: 100px; height: 100px"
                      :src="imgUrl"
                      :zoom-rate="1.2"
                      :initial-index="4"
                      fit="cover"
                  />
                </div>
              </el-col>
              <el-col :span="12">
                <el-form-item label="用户头像" prop="logoUrl">
                  <el-upload
                      ref="upload"
                      :limit="1"
                      accept=".jpg, .png"
                      :action="upload.url"
                      :headers="upload.headers"
                      :file-list="upload.fileList"
                      :on-preview="handleFileUploadProgress"
                      :on-success="handleFileSuccess"
                      :on-remove="handleRemoveFile"
                      :auto-upload="false">
                    >
                    <template #trigger>
                      <el-button type="primary">选取文件</el-button>
                    </template>
                    <el-button class="ml-3" type="success" @click="handleSubmitUpload">
                      上传文件
                    </el-button>
                    <template #tip>
                      <div class="el-upload__tip">
                        只能上传jpg/png文件，且不超过500kb
                      </div>
                    </template>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="用户标识" prop="userCode">
                  <el-input v-model="form.userCode" clearable placeholder="请输入用户标识"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="首页视图" prop="dashboard">
                  <el-select v-model="form.dashboard" clearable placeholder="请选择首页视图">
                    <el-option key="0" label="组件视图" value="0"/>
                    <el-option key="1" label="应用视图" value="1"/>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="用户账户" prop="username">
                  <el-input v-model="form.username" clearable placeholder="请输入用户账户"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="用户昵称" prop="nickName">
                  <el-input v-model="form.nickName" clearable placeholder="请输入用户昵称"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="联系电话" prop="phone">
                  <el-input v-model="form.phone" clearable placeholder="请输入联系电话"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系邮箱" prop="email">
                  <el-input v-model="form.email" clearable placeholder="请输入联系邮箱"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="登录密码" prop="password">
                  <el-input type="password" v-model="form.password" clearable placeholder="请输入登录密码"
                            :disabled="title === '修改用户'"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属部门" prop="deptId">
                  <el-cascader v-model="form.deptId" :options="deptList" :props="formDeptProps"
                               :show-all-levels="false"
                               clearable style="width: 100%;" placeholder="请选择所属部门"></el-cascader>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="岗位" prop="postIds">
                  <el-select style="width: 100%;" v-model="form.postIds" multiple placeholder="请选择岗位">
                    <el-option
                        v-for="post in postList"
                        :key="post.postId"
                        :label="post.postName"
                        :value="post.postId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="角色" prop="roleIds">
                  <el-select style="width: 100%;" v-model="form.roleIds" multiple placeholder="请选择角色">
                    <el-option
                        v-for="role in roleList"
                        :key="role.roleId"
                        :label="role.roleName"
                        :value="role.roleId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="性别" prop="sex">
                  <el-radio-group v-model="form.sex" size="mini">
                    <el-radio :label="0" border>女</el-radio>
                    <el-radio :label="1" border>男</el-radio>
                    <el-radio :label="2" border>保密</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="是否有效" prop="status">
                  <el-switch v-model="form.status" :active-value="true" :inactive-value="false"></el-switch>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input type="textarea" v-model="form.remark" clearable placeholder="请输入备注"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <template #footer>
            <el-button type="primary" :loading="saveing" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </template>
        </el-dialog>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
export default {
  name: "User",
  data() {
    return {
      // 部门遮罩层
      deptLoading: true,
      // 搜索用的部门名称
      deptName: '',
      // 部门列表数据
      deptList: [],
      // 角色列表数据
      roleList: [],
      // 岗位列表数据
      postList: [],
      // 部门 props
      deptProps: {
        label: (data) => {
          return data.deptName
        }
      },
      // 部门 props
      formDeptProps: {
        value: "deptId",
        label: "deptName",
        emitPath: false,
        checkStrictly: true
      },
      // 显示搜索条件
      showSearch: true,
      // 分页总条数
      total: 0,
      // 查询参数
      queryParams: {
        deptId: undefined,
        username: undefined,
        status: undefined,
        pageNum: 1,
        pageSize: 10
      },
      // 遮罩层
      loading: true,
      // 用户列表数据
      userList: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 表格配置
      config: {
        // 表格大小
        size: "default",
        // 表格边框
        border: true,
        // 表格斑马图纹
        stripe: true
      },
      // 保存遮罩层
      saveing: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userCode: [
          {required: true, message: '请输入用户标识', trigger: 'blur'}
        ],
        dashboard: [
          {required: true, message: '请选择首页视图', trigger: 'blur'}
        ],
        username: [
          {required: true, message: '请输入用户账户', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入登录密码', trigger: 'blur'}
        ],
        deptId: [
          {required: true, message: '请选择所属部门', trigger: 'blur'}
        ],
        nickName: [
          {required: true, message: '请输入用户昵称', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请输入联系电话', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入联系邮箱', trigger: 'blur'}
        ],
        sex: [
          {required: true, message: '请选择用户性别', trigger: 'blur'}
        ],
        status: [
          {required: true, message: '请选择用户状态', trigger: 'blur'}
        ],
      },
      columns: [
        {key: 0, label: `用户标识`, visible: true},
        {key: 1, label: `用户名称`, visible: true},
        {key: 2, label: `用户昵称`, visible: true},
        {key: 3, label: `联系电话`, visible: true},
        {key: 4, label: `联系邮箱`, visible: true},
        {key: 5, label: `用户性别`, visible: true},
        {key: 6, label: `状态`, visible: true},
        {key: 7, label: `创建时间`, visible: false},
        {key: 8, label: `备注`, visible: true}
      ],
      // 上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {Authorization: this.$TOOL.getJti()},
        // 上传的地址
        url: this.$CONFIG.API_URL + "/platform/file/uploadImage",
        // 上传的文件列表
        fileList: []
      },
      imgUrl: null
    };
  },
  created() {
    this.getList();
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      if (this.deptList.length === 0) {
        this.deptLoading = true;
        this.$API.dept.pageListDept.get({status: true}).then(response => {
          if (response.status) {
            this.deptList = response.data.records;
            this.deptLoading = false;
          } else {
            this.$message.warning(response.msg);
          }
        });
      }
      if (this.roleList.length === 0) {
        this.$API.role.pageListRole.get({status: true}).then(response => {
          if (response.status) {
            this.roleList = response.data.records;
          } else {
            this.$message.warning(response.msg);
          }
        })
      }
      if (this.postList.length === 0) {
        this.$API.post.pageListPost.get({status: true}).then(response => {
          if (response.status) {
            this.postList = response.data.records;
          } else {
            this.$message.warning(response.msg);
          }
        });
      }
      this.$API.user.pageListUser.get(this.queryParams).then(response => {
        if (response.status) {
          this.userList = response.data.records;
          this.total = response.data.total;
        } else {
          this.$message.warning(response.msg);
        }
        this.loading = false;
      });
    },
    /** 筛选节点 */
    deptFilterNodeMethod(value, data) {
      if (!value) return true;
      return data.deptName.indexOf(value) !== -1;
    },
    /** 节点单击事件 */
    handleDeptClick(data) {
      this.queryParams.deptId = data.deptId;
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.deptId = undefined
      this.$refs["queryForm"].resetFields();
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户";
      this.$API.config.getPlatformConfigValueWithDefault.get('INIT_PASSWORD', 'INIT_PASSWORD', '123456').then(response => {
        if (response.status) {
          this.form.password = response.data
        } else {
          this.$message.warning(response.msg);
        }
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const userId = row.userId || this.ids
      this.$API.user.getUserById.get(userId).then(response => {
        if (response.status) {
          this.form = response.data;
          // 默认密码不能修改 这里随便设置一个值 后端不会真的修改
          this.form.password = '123456';
          if (this.form.avatar) {
            this.imgUrl = this.form.avatar
            this.upload.fileList = [{name: '用户头像', url: this.form.avatar}];
          }
          this.open = true;
          this.title = "修改用户";
        } else {
          this.$message.warning(response.msg);
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId ? [row.userId] : this.ids;
      this.$confirm(`确定删除选中的 ${userIds.length} 项吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        this.$API.user.delUsers.delete(userIds).then(response => {
          if (response.status) {
            this.$message.success(response.msg);
            this.getList();
          } else {
            this.$alert(response.msg, "提示", {type: 'error'});
          }
        });
      }).catch(() => {
      })
    },
    /** 表单重置 */
    reset() {
      this.form = {
        userId: "",
        userCode: "",
        username: "",
        password: "",
        deptId: "",
        nickName: "",
        phone: "",
        email: "",
        sex: 2,
        avatar: "",
        remark: "",
        status: true,
        roleIds: [],
        postIds: []
      };
      this.upload.fileList = [];
      this.imgUrl = null;
      this.$nextTick(() => {
        if (this.$refs['form']) {
          this.$refs['form'].clearValidate();
          this.$refs['form'].resetFields();
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.saveing = true;
          // 如果 ID 存在就是更新
          if (this.form.userId) {
            this.$API.user.editUser.put(this.form).then(response => {
              if (response.status) {
                this.$message.success(response.msg);
                this.saveing = false;
                this.open = false;
                this.getList();
              } else {
                this.$alert(response.msg, "提示", {type: 'error'});
                this.saveing = false;
              }
            });
          } else {
            // 不存在就是新增
            this.$API.user.addUser.post({
              userCode: this.form.userCode,
              username: this.form.username,
              password: this.$TOOL.crypto.rsaEncrypt(this.form.password),
              deptId: this.form.deptId,
              nickName: this.form.nickName,
              phone: this.form.phone,
              email: this.form.email,
              sex: this.form.sex,
              avatar: this.form.avatar,
              remark: this.form.remark,
              status: this.form.status,
              roleIds: this.form.roleIds,
              postIds: this.form.postIds
            }).then(response => {
              if (response.status) {
                this.$message.success(response.msg);
                this.saveing = false;
                this.open = false;
                this.getList();
              } else {
                this.$alert(response.msg, "提示", {type: 'error'});
                this.saveing = false;
              }
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.saveing = false;
      this.reset();
    },
    // 文件提交处理
    handleSubmitUpload() {
      this.$refs.upload.submit();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.form.avatar = response.data.fileUrl;
      this.imgUrl = response.data.fileUrl
      this.$message.success(response.msg);
    },
    handleRemoveFile() {
      this.imgUrl = null
    }
  }
};
</script>
